package com.wanyang.service;

import com.wanyang.aliyun.service.AliyunSmsService;
import com.wanyang.aliyun.configure.SmsProperties;
import com.wanyang.dto.AliyunSmsDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Autowired
    private AliyunSmsService aliyunSmsService;

    @Override
    public void send(String mobile, String scenes) {
        String smsCode = generateSmsCode();

        stringRedisTemplate.opsForValue().set(getCacheKey(mobile, scenes), smsCode, 10, TimeUnit.MINUTES);

        SmsProperties smsProperties = SmsProperties.getInstance();

        // test mode 不发送验证码
//        if (!smsProperties.isTestMode()) {
            AliyunSmsDTO aliyunSmsDTO = new AliyunSmsDTO();

            SmsProperties.Template template = smsProperties.getTemplates().stream()
                    .filter(e -> e.getType().equals(scenes)).findFirst().orElseThrow(RuntimeException::new);

            aliyunSmsDTO.setMobile(mobile);
            aliyunSmsDTO.setTemplateCode(template.getTemplateCode());
            aliyunSmsDTO.setTemplateParam(String.format("{\"code\":%s}", smsCode));
            aliyunSmsDTO.setSignName(template.getSignName());
            aliyunSmsService.sendSms(aliyunSmsDTO);
//        }
    }

    private String getCacheKey(String mobile, String scenes) {
        return "SMS_" + scenes + "_" + mobile;
    }

    private String generateSmsCode() {
        return SmsProperties.getInstance().isTestMode() ? "1111" : String.format("%04d",new Random().nextInt(9999));
    }

    @Override
    public boolean validSmsCode(String mobile, String smsCode, String scenes) {
        String cacheKey;
        String redisSmsCode = stringRedisTemplate.opsForValue().get(cacheKey = getCacheKey(mobile, scenes));

        boolean result = StringUtils.equals(smsCode, redisSmsCode);

        if (result) {
            stringRedisTemplate.delete(cacheKey);
        }

        return result;
    }

}
